<script setup lang="ts">
import {
  type ComponentInternalInstance,
  getCurrentInstance,
  onMounted,
  ref,
} from 'vue';

import { EBuilder, type PageSchema } from 'epic-designer';

defineOptions({
  name: 'SystemApp',
});
const { app } = defineProps({
  app: {
    default: () => ({}),
    type: Object,
  },
});
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const baseUrl = proxy?.$config.baseUrl;
const builderRef = ref<InstanceType<typeof EBuilder>>();
const pageSchema = ref<PageSchema>({
  schemas: [
    {
      componentProps: {
        name: '默认页面',
        style: {
          padding: '16px',
        },
      },
      id: 'root',
      label: '页面',
      type: 'page',
      children: [],
    },
  ],
});
const loadPageSchema = async () => {
  if (!app || !app?.pid) return;
  const id = (app?.key as string).replace('system_', '');
  try {
    const url = `${baseUrl}/design/project/${id}`;
    const mapping = await fetch(url, {
      method: 'GET',
    });

    const res = await mapping.json();
    const { code, data } = res;
    if (code === 200 && data) {
      pageSchema.value =
        typeof data === 'string'
          ? (JSON.parse(data) as PageSchema)
          : (data as PageSchema);
    }
    // setTimeout(() => {
    //   builderRef.value?.setData(schemas);
    // }, 200);
  } catch (error) {
    console.log(error);
  }
};
onMounted(async () => {
  await loadPageSchema();
});
</script>
<template>
  <div class="wos-system-app">
    <EBuilder ref="builderRef" :page-schema="pageSchema" />
  </div>
</template>
<style lang="scss">
@import url('./css/app.scss');
</style>
